import React, { Component } from 'react'
import store from '../stateFactory/Store'
class SummaryContainer extends Component {
  constructor (props) {
    super(props)
    this.onChange = this.onChange.bind(this)
    this.state = this.getOwnState()
  }
  getOwnState () {
    const state = store.getState()
    let sum = 0
    for (let x in state) {
      if (state.hasOwnProperty(x)) {
        sum = sum + state[x]
      }
    }
    return {sum, ...state}
  }
  onChange () {
    this.setState(this.getOwnState())
  }
  // 保持组件内state与store中的一致
  componentDidMount () {
    store.subscribe(this.onChange)
  }
  componentWillUnmount () {
    store.unsubscribe(this.onChange)
  }
  render () {
    return (
      <Summary sum={this.state.sum} />
    )
  }
}
class Summary extends Component {
  render () {
    const {sum} = this.props
    return (
      <p>total: {sum}</p>
    )
  }
}
export default SummaryContainer